let pieceApi = {}

function makePiece(piece) {
	piece.draggable = 'true'
	piece.style.position = 'absolute'

	piece.onmousedown = function (e) {
		e = e || window.event
		e.preventDefault()
		let posX = e.clientX
		let posY = e.clientY
		document.onmouseup = function (e) {
			e = e || window.event
			e.preventDefault()
			document.onmouseup = null
			document.onmousemove = null
		}
		document.onmousemove = function (e) {
			e = e || window.event
			e.preventDefault()
			let deltaPosX = e.clientX - posX
			let deltaPosY = e.clientY - posY
			posX = e.clientX
			posY = e.clientY
			piece.style.left = (piece.offsetLeft + deltaPosX).toFixed(0) + 'px'
			piece.style.top = (piece.offsetTop + deltaPosY).toFixed(0) + 'px'
		}
	}

	piece.ontouchstart = function (e) {
		e = e || window.event
		e.preventDefault()
		let posX = e.touches[0].clientX
		let posY = e.touches[0].clientY
		console.log(posX, posY)
		document.ontouchend = function (e) {
			e = e || window.event
			e.preventDefault()
			document.ontouchend = null
			document.ontouchmove = null
		}
		document.ontouchmove = function (e) {
			e = e || window.event
			e.preventDefault()
			let deltaPosX = e.touches[0].clientX - posX
			let deltaPosY = e.touches[0].clientY - posY
			posX = e.touches[0].clientX
			posY = e.touches[0].clientY
			piece.style.left = (piece.offsetLeft + deltaPosX).toFixed(0) + 'px'
			piece.style.top = (piece.offsetTop + deltaPosY).toFixed(0) + 'px'
		}
	}

	if (piece.id) {
		if (typeof pieceApi[piece.id] !== 'object')
			pieceApi[piece.id] = {}
		pieceApi[piece.id].moveTo = function (x, y) {
			piece.style.left = x.toFixed(0) + 'px'
			piece.style.top = y.toFixed(0) + 'px'
		}
	}
}

function makeDice6(piece) {
	let number = 0
	let faces = piece.children[0].children
	let faceCount = faces.length
	function displayNumber() {
		for (let i = 0; i < faceCount; ++i)
			faces[i].style.display = (i == number) ? '' : 'none'
	}
	displayNumber()

	piece.ondblclick = function (e) {
		e = e || window.event
		e.preventDefault()
		function roll(times) {
			if (times <= 0) return
			number = Math.floor(Math.random() * faceCount)
			displayNumber()
			setTimeout(function () { roll(times - 1) }, 100)
		}
		roll(10)
	}

	piece.oncontextmenu = function (e) {
		e = e || window.event
		e.preventDefault()
		if ((++number) >= faceCount)
			number = 0
		displayNumber()
	}

	if (piece.id) {
		if (typeof pieceApi[piece.id] !== 'object')
			pieceApi[piece.id] = {}
		pieceApi[piece.id].setNumber = function (n) {
			number = n
			displayNumber()
		}
	}
}

let pieces = document.body.children
let pieceCount = pieces.length
for (let i = 0; i < pieceCount; ++i) {
	let piece = pieces[i]
	makePiece(piece)
	if (piece.getAttribute('dice') == '6')
		makeDice6(piece)
}